package dhm.com.dhmshop.updata.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.dhmshop.R;
import dhm.com.dhmshop.adapter.mine.FunctionAdapter;
import dhm.com.dhmshop.adapter.mine.ShowImageAdapter;
import dhm.com.dhmshop.base.BaseActiity;
import dhm.com.dhmshop.base.Presenter.PressenterImpl;
import dhm.com.dhmshop.base.netWork.Constant;
import dhm.com.dhmshop.base.netWork.LoginContract;
import dhm.com.dhmshop.entity.Bean;
import dhm.com.dhmshop.entity.FunctionBean;
import dhm.com.dhmshop.entity.GetAllOrder;
import dhm.com.dhmshop.entity.Result;
import dhm.com.dhmshop.entity.ResultDetailCallback;
import dhm.com.dhmshop.utils.BitmapUtil;
import dhm.com.dhmshop.utils.SpUtils;
import dhm.com.dhmshop.view.mine.order.ShowevaluateActivity;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;

public class SaleserviceActivity extends BaseActiity implements LoginContract.IView {

    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.text_type)
    TextView textType;
    @BindView(R.id.text_result)
    TextView textResult;
    @BindView(R.id.high_money)
    TextView highMoney;
    @BindView(R.id.tishi)
    EditText tishi;
    @BindView(R.id.conten)
    TextView conten;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.jine)
    LinearLayout jine;
    @BindView(R.id.refundMoney)
    EditText refundMoney;
    private PressenterImpl pressenter;
    private FunctionBean functionBean;
    private GetAllOrder.DataBean bean;
    private ShowImageAdapter showImageAdapter;


    @Override
    protected int getLayout() {
        return R.layout.activity_saleservice;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        Intent intent = getIntent();
        bean = (GetAllOrder.DataBean) intent.getSerializableExtra("bean");
        pressenter = new PressenterImpl();
        pressenter.attachView(this);

    }

    @Override
    protected void initData() {
        showImageAdapter = new ShowImageAdapter(images, this);
        showImageAdapter.setaddClick(new ShowImageAdapter.OnIntentClick() {
            @Override
            public void item() {
                pickImage();
            }
        });

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(gridLayoutManager);
        recy.setAdapter(showImageAdapter);
        image.setImageURI(Constant.PATH + "/" + bean.getList().get(0).getGoodsImg());
        name.setText(bean.getList().get(0).getGoodsName());

        float highmpney = 0;
        for (int i = 0; i < bean.getList().size(); i++) {
            highmpney = highmpney + Float.parseFloat(bean.getList().get(i).getGoodsPrice()) * Integer.parseInt(bean.getList().get(i).getGoodsNum());
        }
        highMoney.setText(highmpney+"");

    }

    @Override
    public void requesta(Object data) {
        if (data instanceof FunctionBean) {
            functionBean = (FunctionBean) data;
            showPopwindow();
        }

    }

    @Override
    public void fail(String error) {

    }

    String type = "";

    @OnClick({R.id.back, R.id.question, R.id.result, R.id.commit})
    public void onViewClicked(View view) {
        Map<String, String> map;
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.question:
                functionBean = new FunctionBean();
                FunctionBean.DataBean beans = new FunctionBean.DataBean();
                List<FunctionBean.DataBean> list = new ArrayList<>();
                beans.setDataName("退货退款");
                beans.setId(0);
                beans.setChecked(true);
                list.add(beans);
                beans = new FunctionBean.DataBean();
                beans.setDataName("退款");
                beans.setId(1);
                list.add(beans);
                beans = new FunctionBean.DataBean();
                beans.setDataName("换货");
                beans.setId(2);
                list.add(beans);
                functionBean.setData(list);
                type = "type";
                showPopwindow();
                break;
            case R.id.result:
                type = "result";
                map = new HashMap<>();
                map.put("token", Constant.TOKEN);
                pressenter.sendMessage(SaleserviceActivity.this, Constant.RejrctReason, map, FunctionBean.class);
                break;
            case R.id.commit:

                String content = tishi.getText().toString();

                if (content==null||content.equals("")){
                    Toast.makeText(this, "请输入问题描述", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                String ids = "";
                for (int i = 0; i < bean.getList().size(); i++) {
                    ids = ids + bean.getList().get(i).getId() + ",";
                }
                ids = ids.substring(0, ids.length() - 1);

                String uid = SpUtils.getString(this, "uid");
                Map<String, File> files = new HashMap<>();
                if (images.size() == 0) {
                    map = new HashMap<>();
                    map.put("token", Constant.TOKEN);
                    map.put("orderId", bean.getOrderId() + "");
                    map.put("ids", ids);
                    map.put("serviceType", serviceType);
                    map.put("uid", uid);
                    map.put("serviceRemark", content);
                    map.put("goodsServiceType", goodsServiceType);
                    if (!goodsServiceType.equals("2")) {
                        String cont = refundMoney.getText().toString();
                        if (cont == null || cont.equals("")) {
                            Toast.makeText(this, "请输入退款金额", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        map.put("refundMoney", bean.getList().get(0).getGoodsId() + "");
                    }
                    for (int i = 0; i < bean.getList().size(); i++) {
                        map.put("goodsNum_" + bean.getList().get(i).getId(), bean.getList().get(i).getGoodsNum() + "");
                    }
                    pressenter.sendMessage(SaleserviceActivity.this, Constant.SaleComments, map, Bean.class);
                } else {
                    try {
                        for (int i = 0; i < images.size(); i++) {
                            files.put(bitmapToString(images.get(i)), new File(bitmapToString(images.get(i))));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    PostFormBuilder postFormBuilder = OkHttpUtils.post().url(Constant.PATH + Constant.SaleComments)
                            .addParams("token", Constant.TOKEN)
                            .addParams("ids", ids)
                            .addParams("serviceType", serviceType)
                            .addParams("goodsServiceType", goodsServiceType)
                            .addParams("orderId", bean.getOrderId() + "")
                            .addParams("uid", SpUtils.getString(SaleserviceActivity.this, "uid") + "")
                            .addParams("serviceRemark", content)
                            .files("image[]", files);
                    if (!goodsServiceType.equals("2")) {
                        String cont = refundMoney.getText().toString();
                        if (cont == null || cont.equals("")) {
                            Toast.makeText(this, "请输入退款金额", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        postFormBuilder.addParams("refundMoney", bean.getList().get(0).getGoodsId() + "");
                    }
                    for (int i = 0; i < bean.getList().size(); i++) {
                        postFormBuilder.addParams("goodsNum_" + bean.getList().get(i).getId(), bean.getList().get(i).getGoodsNum() + "");
                    }


                    postFormBuilder.build().execute(new ResultDetailCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Toast.makeText(SaleserviceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(Result response, int id) {
                            Toast.makeText(SaleserviceActivity.this, response.getMessage(), Toast.LENGTH_LONG).show();
                            if (response != null && response.getCode() == 1) {
                                finish();
                            }
                        }
                    });

                }


                break;
            default:
        }
    }

    private String serviceType = "";
    private String goodsServiceType = "0";
    private FunctionAdapter functionAdapter;
    private PopupWindow popWindow;

    private void showPopwindow() {
        View popView = View.inflate(SaleserviceActivity.this, R.layout.popup_questiontype, null);
        Button sure = popView.findViewById(R.id.sure);
        RecyclerView recy = popView.findViewById(R.id.recy);
        LinearLayoutManager manager = new LinearLayoutManager(SaleserviceActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        functionAdapter = new FunctionAdapter(SaleserviceActivity.this);
        functionAdapter.setaddClick(new FunctionAdapter.OnShopClick() {
            @Override
            public void item(List<FunctionBean.DataBean> beanList) {
                functionBean.setData(beanList);
                functionAdapter.setShopList(functionBean.getData());
            }
        });

        recy.setAdapter(functionAdapter);
        recy.setLayoutManager(manager);
        functionAdapter.setShopList(functionBean.getData());
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (type.equals("type")) {
                    for (int i = 0; i < functionBean.getData().size(); i++) {
                        if (functionBean.getData().get(i).isChecked()) {
                            goodsServiceType = functionBean.getData().get(i).getDataVal() + "";
                            textType.setText(functionBean.getData().get(i).getDataName());
                            if (goodsServiceType.equals("2")){
                                jine.setVisibility(View.GONE);
                            }else {
                                jine.setVisibility(View.VISIBLE);
                            }

                        }
                    }

                    if (goodsServiceType.equals("")) {
                        Toast.makeText(SaleserviceActivity.this, "售后类型", Toast.LENGTH_SHORT).show();
                        return;
                    }

                } else {
                    for (int i = 0; i < functionBean.getData().size(); i++) {
                        if (functionBean.getData().get(i).isChecked()) {
                            serviceType = functionBean.getData().get(i).getDataVal() + "";
                            textResult.setText(functionBean.getData().get(i).getDataName());
                        }
                    }

                    if (serviceType.equals("")) {
                        Toast.makeText(SaleserviceActivity.this, "申请原因", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }


                popWindow.dismiss();
            }
        });


        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });
        setBackgroundAlpha(0.5f);
        popWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                images.clear();
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                StringBuilder sb = new StringBuilder();
                for (String p : mSelectPath) {
                    sb.append(p);
                    sb.append("\n");
                    Bitmap bitmap = BitmapUtil.getScaleBitmap(p, 0, 0);
                    images.add(bitmap);
                }
                showImageAdapter.showImage(images);
            }
        }
    }

    public String bitmapToString(Bitmap bitmap) {
        //将bitmap转换为uri
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        return img_path;
    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private ArrayList<Bitmap> images = new ArrayList<>();
    private ArrayList<String> mSelectPath;
    private static final int REQUEST_IMAGE = 2;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(SaleserviceActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }


    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {

            int maxNum = 5;
            MultiImageSelector selector = MultiImageSelector.create(SaleserviceActivity.this);
            selector.showCamera(true);
            selector.count(maxNum);
            selector.multi();
            selector.origin(mSelectPath);
            selector.start(SaleserviceActivity.this, REQUEST_IMAGE);
        }
    }


}
